import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_admin/api/odoo/purchase_quality_problem_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/purchase_quality_problem.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/loading_dialog.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:fluttertoast/fluttertoast.dart';

class PurchaseQualityProblemCaurseList extends StatefulWidget {
  final PurchaseQualityProblem? purchaseQualityProblem;
  String? workCode;

  PurchaseQualityProblemCaurseList(
      {required this.purchaseQualityProblem, this.workCode, Key? key})
      : super(key: key);

  @override
  State<PurchaseQualityProblemCaurseList> createState() =>
      _PurchaseQualityProblemCaurseListState();
}

class _PurchaseQualityProblemCaurseListState
    extends State<PurchaseQualityProblemCaurseList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);

  PageModel refusePage = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    setState(() {});
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text(S.of(context).caurseHistory),
      ),
      body: Column(
        children: [
          createHistoryTable(),
          if (widget.workCode != null && widget.workCode != 'ZL')
            historyOPButton(),
        ],
      ),
    );
    return scaffold;
  }

  Future<dynamic> findAll() async {
    List<PurchaseQualityProblem> resultList = [];
    ResponseBodyApi responseBodyApi =
        await PurchaseQualityProblemOdooApi.getCaurseHistory(data: {
      "page": page,
      "domainList": [
        ['problem_id', '=', int.parse(widget.purchaseQualityProblem!.id!)]
      ],
    });

    ResponseBodyApi refuseResponseBodyApi =
        await PurchaseQualityProblemOdooApi.getRefuceHistory(data: {
      "page": refusePage,
      "domainList": [
        ['problem_id', '=', int.parse(widget.purchaseQualityProblem!.id!)]
      ],
    });
    if (responseBodyApi.success!) {
      // resultList = responseBodyApi.data.map<PurchaseQualityProblem>((e) {
      //   return PurchaseQualityProblem.fromMap(e);
      // }).toList();

      var refuseList = (refuseResponseBodyApi.data as PageModel).records;
      var caurseList = (responseBodyApi.data as PageModel).records;

      for (var i = 0; i < caurseList.length; i++) {
        caurseList[i].putIfAbsent('reason',
            () => refuseList.length > i ? refuseList[i]['resaon'] : null);
      }

      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      // setState(() {});
    } else {
      Fluttertoast.showToast(msg: '获取记录出错了，具体错误原因：${responseBodyApi.message}');
    }
  }

  _loadData() async {
    tableKey.currentState?.pageTo(0);
    findAll();
  }

  createHistoryTable() {
    return CryDataTable(
      selectable: (m) {
        return false;
      },
      showCheckboxColumn: false,
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        // DataColumn(
        //   label: Text('文档编号'),
        //   onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        // ),
        // DataColumn(
        //   label: Text('产品名称'),
        //   // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        // ),
        DataColumn(
          label: Text(
            '客户原因分析',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text(
            '改进措施',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text(
            '退回意见',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text(
            '创建人',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text(
            '创建日期',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        var name = '';
        var uid = m['create_uid'];
        if (uid != null && uid is List) {
          name = uid.length > 0 ? uid[1] : '--';
        }
        var caurse = '--';
        var ca = m['causeanalysis'];
        if (ca != null && ca is String) {
          caurse = ca;
        }
        var solution = '--';
        var so = m['rectificationmeasures'];
        if (so != null && so is String) {
          solution = so;
        }
        var reason = '--';
        var refuseReason = m['reason'];
        if (refuseReason != null && refuseReason is String) {
          reason = refuseReason;
        }
        return [
          DataCell(Container(
              child: Text(
            caurse,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ))),
          DataCell(Container(
            child: Text(
              solution,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          )),
          DataCell(Text(reason)),
          DataCell(Text(name)),
          DataCell(Text(Utils.timeUTC(m['create_date']) ?? '--')),
        ];
      },
    );
  }

  historyOPButton() {
    return CryButtonBar(
      children: <Widget>[
        // CryButtons.query(context, () => _query()),
        CryButton(
          label: "新增问题原因分析",
          onPressed: () {
            showInputCaurseDialog();
          },
          iconData: Icons.add,
        ),
      ],
    );
  }

  void showInputCaurseDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(child: QualityCaurseAnalyse()),
    ).then((v) {
      if (v != null) {
        // 返回原因分析填写内容，然后提交
        // Fluttertoast.showToast(msg: '提交的内容为：$v');
        // 走接口，将问题原因提交到后台，然后提交成功之后，重新获取列表数据
        submitCaurse(v);
      }
    });
  }

  void submitCaurse(v) async {
    var cccaurse = v['cccause'];
    var lccaurse = v['lccause'];
    var ccsolution = v['ccsolution'];
    var lcsolution = v['lcsolution'];
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return LoadingDialog(
            title: "正在提交...",
            isCancel: false,
          );
        });
    ResponseBodyApi responseBodyApi =
        await PurchaseQualityProblemOdooApi.submitCaurse({
      'problem_id': int.parse(widget.purchaseQualityProblem!.id!),
      'causeanalysis': '$cccaurse-$lccaurse',
      'rectificationmeasures': '$ccsolution-$lcsolution'
    });
    if (responseBodyApi.success!) {
      widget.purchaseQualityProblem!.causeanalysis = '$cccaurse-$lccaurse';
      widget.purchaseQualityProblem!.rectificationmeasures =
          '$ccsolution-$lcsolution';
      widget.purchaseQualityProblem!.isPush = '0';
      widget.purchaseQualityProblem!.status =
          PurchaseQualityProblem.SUBMIT_CAURSE;
      ResponseBodyApi updateResponseBodyApi =
          await PurchaseQualityProblemOdooApi.saveOrUpdate(
              widget.purchaseQualityProblem!.toOdooMap());
      if (responseBodyApi.success! && updateResponseBodyApi.success!) {
        Navigator.pop(context);
        _loadData();
      } else {
        Fluttertoast.showToast(msg: '提交失败！失败原因：${responseBodyApi.message}');
      }
    }
  }
}

/**
 * 新增原因分析弹窗界面
 */
class QualityCaurseAnalyse extends StatelessWidget {
  QualityCaurseAnalyse({Key? key}) : super(key: key);

  var cccaurse = TextEditingController();
  var lcCaurse = TextEditingController();
  var fixccSolution = TextEditingController();
  var fixlcSolution = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 650,
      child: Scaffold(
        appBar: AppBar(
          title: Text('新增原因分析'),
        ),
        body: Column(
          children: [
            Container(
              margin: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '产出原因',
                    style: TextStyle(color: Colors.blue),
                  ),
                  Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        border: Border.all(width: 1, color: Colors.blue)),
                    child: TextField(
                      minLines: 5,
                      maxLines: 5,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '请输入产出原因分析',
                          hintStyle: TextStyle(color: Colors.blueGrey)),
                      controller: cccaurse,
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    '流出原因',
                    style: TextStyle(color: Colors.blue),
                  ),
                  Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        border: Border.all(width: 1, color: Colors.blue)),
                    child: TextField(
                      minLines: 5,
                      maxLines: 5,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '请输入流出原因分析',
                          hintStyle: TextStyle(color: Colors.blueGrey)),
                      controller: lcCaurse,
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    '产出原因改进措施',
                    style: TextStyle(color: Colors.blue),
                  ),
                  Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        border: Border.all(width: 1, color: Colors.blue)),
                    child: TextField(
                      minLines: 5,
                      maxLines: 5,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '请输入产出原因改进措施',
                          hintStyle: TextStyle(color: Colors.blueGrey)),
                      controller: fixccSolution,
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    '流出原因改进措施',
                    style: TextStyle(color: Colors.blue),
                  ),
                  Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        border: Border.all(width: 1, color: Colors.blue)),
                    child: TextField(
                      minLines: 5,
                      maxLines: 5,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '请输入流出原因改进措施',
                          hintStyle: TextStyle(color: Colors.blueGrey)),
                      controller: fixlcSolution,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CryButton(
                  label: "提交",
                  onPressed: () {
                    if (cccaurse.text.isNotEmpty &&
                        fixccSolution.text.isNotEmpty &&
                        lcCaurse.text.isNotEmpty &&
                        fixlcSolution.text.isNotEmpty) {
                      Navigator.pop(context, {
                        'cccause': cccaurse.text,
                        'lccause': cccaurse.text,
                        'ccsolution': fixccSolution.text,
                        'lcsolution': fixlcSolution.text
                      });
                    } else {
                      Fluttertoast.showToast(msg: '请完整输入问题原因分析以及改进措施');
                    }
                  },
                  iconData: Icons.add,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
